package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BaseException;
import com.sky.mapper.CartMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.CartSevice;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Service
public class CartServiceImpl implements CartSevice {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 添加购物车
     *
     * @param dto
     * @return
     */
    @Override
    public void add(ShoppingCartDTO dto) {
        ShoppingCart cart = new ShoppingCart();
        BeanUtils.copyProperties(dto, cart);
        cart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = cartMapper.getCart(cart);
        if (!CollectionUtils.isEmpty(list) && list.size() == 1) {
            ShoppingCart shoppingCart = list.get(0);
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);
            Integer count = cartMapper.updateCart(shoppingCart);
            if(count<1){
                throw new BaseException("修改购物车数据失败");
            }
        }

        else {
            DishVO dishVo = dishMapper.selectById(dto.getDishId());
            if (dishVo == null) {
                Setmeal setmeal = setmealMapper.getById(Integer.valueOf(String.valueOf(dto.getSetmealId())));
                cart.setName(setmeal.getName());
                cart.setImage(setmeal.getImage());
                cart.setAmount(setmeal.getPrice());
                cart.setNumber(1);
                cart.setCreateTime(LocalDateTime.now());
            } else {
                cart.setName(dishVo.getName());
                cart.setImage(dishVo.getImage());
                cart.setAmount(dishVo.getPrice());
                cart.setNumber(1);
                cart.setCreateTime(LocalDateTime.now());
            }
            cartMapper.add(cart);
        }
    }
    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> getList() {
        List<ShoppingCart> cartList =  cartMapper.getList();
        return cartList;
    }

    @Override
    public void delete() {
        Long userId = BaseContext.getCurrentId();
        cartMapper.delete(userId);
    }
}
